
class CheckoutController < ApplicationController 
  include Wicked::Wizard  
  require 'mail'
  layout "sidebar"
  
  # order of the wizard
  steps :order_person, :order_options, :order_summary, :order_invoice
  
  # Shows the current cart
  def show
    @cart = current_cart
    @checkout = current_checkout
    
    case step
      when :order_invoice
        @order = Order.find(:last)
    end
    
    render_wizard
  end
  
  # updates the current cart
  def update
    @cart = current_cart
    @checkout = current_checkout
    
    if params[:checkout]
      params[:checkout][:status] = step.to_s
      @checkout.attributes = params[:checkout]
    end
       
    # as it is a wizard, the fields will be loaded
    # on the specified step   
    case step
      when :order_summary        
        @order = Order.new
        @order.name = @checkout.name
        @order.address = @checkout.address
        @order.email = @checkout.email
        @order.pay_type = @checkout.pay_type
        @order.shipping_type = @checkout.shipping_type
        @order.is_gift = @checkout.is_gift
        @order.add_line_items_from_cart(current_cart)
        
        if @order.save
          
          # send a mail to the user
          mail = Mail.new do
            from    'orders@studentsbookshop.ch'
            subject 'Order confirmation'
            body    'test'
          end
          
          mail[:to]    = @checkout.email
          
          mail.to_s
          
          Cart.destroy(session[:cart_id])
          Checkout.destroy(session[:checkout_id])
          session[:cart_id] = nil          
          session[:checkout_id] = nil
          
        end
    end
        
    render_wizard @checkout
  end
    
  # Method to forward to the main page after checkout  
  def finish_wizard_path
    store_index_path
  end
end